package com.bestcem.xm.member.controller;

import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.member.controller.vo.ExtendFieldVO;
import com.bestcem.xm.member.controller.vo.FieldItemVO;
import com.bestcem.xm.member.grpc.service.param.extendfield.ListDisplayFieldEnumItemsParam;
import com.bestcem.xm.member.service.ExtendFieldService;
import com.bestcem.xm.member.service.dto.ExtendFieldEnumItemDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author dc.wang <dc.wang@idiaoyan.com>
 * @version V1.0
 * @description 扩展字段web接口控制器
 * @date 2021/8/6
 */
@Slf4j
@RestController
@RequestMapping("/member/field")
public class ExtendFieldController {
    /**
     * 扩展字段服务
     */
    @Autowired
    private ExtendFieldService extendFieldService;

    @GetMapping
    public XmResultJson getFields(@RequestParam("attribute") Integer attribute,
                                  HttpServletRequest request) {
        
        String orgId = SecurityContextHolder.getOrgId();
        ServiceResult<List<ExtendFieldVO>> result = extendFieldService.getFields(attribute, orgId);
        if (result.isSuccess()) {
            return XmResultJson.success(result.getData());
        }
        return XmResultJson.fail(0, "请求失败");
    }

    @GetMapping("/enums")
    public XmResultJson<List<FieldItemVO>> fieldEnums(@RequestParam(name = "fieldid") String fieldId,
                                                       @RequestParam(name = "isdisplay") Integer displayStatus,
                                                                     HttpServletRequest request){
        String orgId = SecurityContextHolder.getUserId();
        ListDisplayFieldEnumItemsParam param = new ListDisplayFieldEnumItemsParam(orgId, fieldId, displayStatus);

        ServiceResult<List<ExtendFieldEnumItemDto>> result = this.extendFieldService.listDisplayFieldEnumItems(param);
        if(!result.isSuccess()){
            return XmResultJson.fail(-1, result.getMsg());
        }

        List<FieldItemVO> data = result.getData().stream().map(this::convert).collect(Collectors.toList());
        return XmResultJson.success(data);
    }

    private FieldItemVO convert(ExtendFieldEnumItemDto dto){
        FieldItemVO res = new FieldItemVO();
        BeanUtils.copyProperties(dto, res);
        return res;
    }
}
